//
//  CargoChooseVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/14.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "CargoChooseVC.h"
#import "KwSegmentView.h"
#import "CargoChooseCell.h"
#import "NWESSRequest.h"
#import "ProductListModel.h"
#import "ESSInventoryModel.h"
#import "KwSegViewHelper.h"
#import "ESSCommitInventoryVC.h"
#import "NWEnquiryPlanRequest.h"
#import "BottomTotalView.h"
#import "OrderDetailListModel.h"

#define kDataProductAttributeId  @"productAttributeId"

#define kDataNumber  @"number"

@interface CargoChooseVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSMutableArray<ProductListModel *> *productTypeArr;  //品类数组

@property (nonatomic,strong) NSMutableArray *productArr;   //品类中产品数组

@property (nonatomic,strong) TPKeyboardAvoidingTableView *tabView;

//当前选中的列表
@property (nonatomic,assign) NSInteger currtenNum;

@property (nonatomic,strong) NSMutableArray *selectCargos;//选中商品model

@property (nonatomic,strong) BottomTotalView *bottomView;

@end

@implementation CargoChooseVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNotification:) name:KwSegViewNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = KwBgColor;
    _currtenNum = 0;
    [self selectCargos];

    NWESSRequest *request = [[NWESSRequest alloc] init];
    [request startRequestGetKWProduct];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            _productTypeArr = [ProductListModel arrayOfModelsFromDictionaries:result];

            //            for (int i = 0; i<_productTypeArr.count; i++)
            //            {
            //                ProductListModel *model = _productTypeArr[i];
            //                NSMutableArray *tempArr = [ESSInventoryModel arrayOfModelsFromDictionaries:model.productList];
            //                model.productList = tempArr;
            self.productArr = _productTypeArr[_currtenNum].productList.mutableCopy;
            //            }

            //订单管理
            if (_type == CargoVCTypeOrderManage)
            {
                //订单管理---------下单或者修改订单 重新选购商品需要将之前商品数传过来
                if (_changeOrderCargos && _changeOrderCargos.count>0)
                {
                    //传递的是详情的model OrderDetailListModel,model不一样,这里采用拿出 ESSInventoryModel修改他的数量
                    if (_isNotDetailModel_Order == NO)
                    {
                        for (OrderDetailListModel *detailModel in _changeOrderCargos)
                        {
                            for (ProductListModel *listModel in _productTypeArr)
                            {
                                NSMutableArray *listArr = [NSMutableArray arrayWithArray:listModel.productList];
                                for (ESSInventoryModel *cargoModel in listArr)
                                {
                                    if ([detailModel.productAttributeId isEqualToString:cargoModel.productAttributeId])
                                    {
                                        cargoModel.totalBox = detailModel.quantity;
                                    }
                                }
                            }
                        }
                    }
                    else //传递的是 ESSInventoryModel
                    {
                        for (ESSInventoryModel *detailModel in _changeOrderCargos)
                        {
                            for (ProductListModel *listModel in _productTypeArr)
                            {
                                NSMutableArray *listArr = [NSMutableArray arrayWithArray:listModel.productList];
                                for (ESSInventoryModel *cargoModel in listArr)
                                {
                                    if ([detailModel.productAttributeId isEqualToString:cargoModel.productAttributeId])
                                    {
                                        cargoModel.totalBox = detailModel.totalBox;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            [self setUpUI];
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}

- (NSMutableArray *)selectCargos
{
    if (!_selectCargos)
    {
        _selectCargos = [NSMutableArray array];
    }
    return _selectCargos;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUpUI
{
    self.title = @"酷我乳业";

    NSMutableArray *titlesArr = [NSMutableArray array];

    for (ProductListModel *model in _productTypeArr)
    {
        [titlesArr addObject:model.typeName];
    }

    //创建顶部菜单
    KwSegmentView *segView =[[KwSegmentView alloc]initWithBtnNames:titlesArr];
    //    segView.btnNames = @[@"营养多",@"乳酸菌",@"冰糖葫芦"];
    segView.frame = CGRectMake(0, 0, self.view.width, 50);
    segView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:segView];
    segView.cancleBlock = ^(){
        [self.view endEditing:YES];
    };

    //创建列表
    _tabView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    _tabView.backgroundColor = KwBgColor;
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabView.estimatedRowHeight = 40.0;
    _tabView.rowHeight = UITableViewAutomaticDimension;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    [self.view addSubview:_tabView];
    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(segView.mas_bottom).offset(1);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];

    __weak typeof(self) weakSelf = self;
    _bottomView = [[BottomTotalView alloc] init];
    _bottomView.block = ^{
        [weakSelf startPlaceAnOrder];
    };
    if (self.isFirstSubmit) {
        [_bottomView.commitBtn setTitle:@"提交库存" forState:UIControlStateNormal];
    }
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(@0);
        make.height.equalTo(@55);
    }];
    NSInteger aTotalBox = 0;
    CGFloat aTotalPrice = 0;
    for (ProductListModel *model in _productTypeArr)
    {

        for (ESSInventoryModel *essModel in model.productList) {
            NSLog(@"========%@",essModel);
            
            if ([essModel.specificationsName isEqual:@"其他"] &&  _OtherType== 2) {
                
            }else
            {  
                aTotalBox = aTotalBox + [essModel.totalBox integerValue];
            }

          
            aTotalPrice = aTotalPrice + [essModel.price floatValue]*[essModel.totalBox integerValue];
        }
    }
    if (_selectCargos)
    {
        [_selectCargos removeAllObjects];
        [self getSelectCargos];
    }
    
    _bottomView.oTotalParaLab.text = [NSString stringWithFormat:@"¥%.2f",aTotalPrice];
    _bottomView.oNumberLab.text = [NSString stringWithFormat:@"共%ld件商品",(long)aTotalBox];

    UISwipeGestureRecognizer *swipeLeftGes = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doSomethingWithGestureRecognizer:)];
    [swipeLeftGes setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [_tabView addGestureRecognizer:swipeLeftGes];

    UISwipeGestureRecognizer *swipeRightGes = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doSomethingWithGestureRecognizer:)];
    [swipeRightGes setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [_tabView addGestureRecognizer:swipeRightGes];
}

- (void)getNotification:(NSNotification *)notification
{
    NSInteger seletIndex = [notification.userInfo[KwNotificationInfoKey_Index] integerValue];
    _currtenNum = seletIndex;
    ProductListModel *model = _productTypeArr[_currtenNum];
    self.productArr = [NSMutableArray arrayWithArray:model.productList];

    for (id objOfArr in self.productArr)
    {
        if (![objOfArr isKindOfClass:[ESSInventoryModel class]])
        {
            ProductListModel *model = _productTypeArr[_currtenNum];
            self.productArr = [ESSInventoryModel arrayOfModelsFromDictionaries:model.productList];
        }
    }

    [_tabView reloadData];
}


- (void)doSomethingWithGestureRecognizer:(UISwipeGestureRecognizer *)swipeGes
{
    if (swipeGes.direction == UISwipeGestureRecognizerDirectionLeft)
    {

        if (_currtenNum < _productTypeArr.count-1 )
        {
            _currtenNum = _currtenNum + 1;
        }
        else
        {
            return;
        }

    }
    else
    {
        if (_currtenNum <= 0)
        {
            return;
        }
        else
        {
            _currtenNum = _currtenNum - 1;
        }
    }

    KwSegViewHelper *kwHelper = [[KwSegViewHelper alloc] init];
    kwHelper.kwSegIndex = _currtenNum;
}

- (void)getSelectCargos
{
    //遍历商品数  进存销
    for (int i = 0; i<_productTypeArr.count; i++)
    {
        ProductListModel *listModel = _productTypeArr[i];
        for (id obj in listModel.productList)
        {
            if ([obj isKindOfClass:[ESSInventoryModel class]])
            {
                ESSInventoryModel *model = obj;
                if (model.totalBox && ![model.totalBox isEqualToString:@"0"])
                {
                    [_selectCargos addObject:model];
                }

            }

        }
    }
}



- (void)startPlaceAnOrder
{
    if (_type == CargoVCTypeESS)
    {
        //初始化库存  进销存
        if (_selectCargos.count>0)
        {
            NSMutableArray *ESSParaArr = [NSMutableArray array];
            for (ESSInventoryModel *model in _selectCargos)
            {
                [ESSParaArr addObject:@{kDataProductAttributeId:model.productAttributeId,kDataNumber:model.totalBox}];
            }

            NSString *dataStr = [CommonTool beJsonStrWithObj:ESSParaArr];
            //初始化库存
            NWESSRequest *request = [[NWESSRequest alloc] init];
            [request startRequestInitInventoryWithUserId:[Singleton shareInstance].userId data:dataStr];
            [request completion:^(id result, NSString *message, id extension, BOOL succ) {
                if (succ)
                {
                    [SVProgressHUD showSuccessWithStatus:@"初始化库存成功"];
                    if (self.reloadBlock) {
                        self.reloadBlock();
                    }
                    //本地数据库更新库存初始化状态
                    [[UserModel getUser] updateInventoryInit];
                    if (self.isFirstSubmit) {
                        [SharedApp setRootViewController];
                    } else {
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                }
            }];
        }
        else
        {
            [SVProgressHUD showInfoWithStatus:@"还未添加商品"];
        }

    }
    else
    {
        //传商品 要货计划  订单管理
        if (_selectCargos.count>0)
        {
            if (_block)
            {
                _block(_selectCargos);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [SVProgressHUD showInfoWithStatus:@"还未添加商品"];
        }
    }
}

#pragma mark tableViewDelegate,DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.productArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"CargoChooseCell";
    CargoChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (!cell)
    {
        cell = [[CargoChooseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    ESSInventoryModel *model = self.productArr[indexPath.row];
    cell.model = self.productArr[indexPath.row];

    __weak CargoChooseCell *weakCell = cell;
    cell.numAddBlock =^(NSString *count){
        weakCell.oNumberParaLab.text  = count;
        NSLog(@"=====%@====%ld",count,(long)indexPath.row);
        ESSInventoryModel *model = [self.productArr objectAtIndex:indexPath.row];
        model.totalBox = count;
       

        [self.productArr replaceObjectAtIndex:indexPath.row withObject:model];

        ProductListModel *typeModel = _productTypeArr[_currtenNum];
        typeModel.productList = self.productArr.copy;
        [_productTypeArr replaceObjectAtIndex:_currtenNum withObject:typeModel];

        if (_selectCargos)
        {
            [_selectCargos removeAllObjects];
            [self getSelectCargos];
        }

        NSInteger aTotalBox = 0;
        CGFloat aTotalPrice = 0;
        for (int i = 0; i<_selectCargos.count; i++)
        {
            ESSInventoryModel *model = _selectCargos[i];
            if ([model.specificationsName isEqual:@"其他"] &&  _OtherType== 2) {
                
            }else
            {
                
                aTotalBox = aTotalBox + [model.totalBox integerValue];
            }
           
            aTotalPrice = aTotalPrice + [model.price floatValue]*[model.totalBox integerValue];
        }
        _bottomView.oTotalParaLab.text = [NSString stringWithFormat:@"¥%.2f",aTotalPrice];
        _bottomView.oNumberLab.text = [NSString stringWithFormat:@"共%ld件商品",(long)aTotalBox];
    };

    cell.numCutBlock =^(NSString *count){

        weakCell.oNumberParaLab.text  = count;

        ESSInventoryModel *model = [self.productArr objectAtIndex:indexPath.row];

        model.totalBox = count;
        
        [self.productArr replaceObjectAtIndex:indexPath.row withObject:model];

        ProductListModel *typeModel = _productTypeArr[_currtenNum];
        typeModel.productList = self.productArr.copy;
        [_productTypeArr replaceObjectAtIndex:_currtenNum withObject:typeModel];

        if (_selectCargos)
        {
            [_selectCargos removeAllObjects];
            [self getSelectCargos];
        }

        NSInteger aTotalBox = 0;
        CGFloat aTotalPrice = 0;
        for (int i = 0; i<_selectCargos.count; i++)
        {
            ESSInventoryModel *model = _selectCargos[i];
            if ([model.specificationsName isEqual:@"其他"] &&  _OtherType== 2) {
                
            }else
            {
                
               aTotalBox = aTotalBox + [model.totalBox integerValue];
            }
            
            aTotalPrice = aTotalPrice + [model.price floatValue]*[model.totalBox integerValue];
        }
        _bottomView.oTotalParaLab.text = [NSString stringWithFormat:@"¥%.2f",aTotalPrice];
        _bottomView.oNumberLab.text = [NSString stringWithFormat:@"共%ld件商品",(long)aTotalBox];

    };

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

- (NSMutableArray *)productArr {
    if (!_productArr) {
        _productArr = [NSMutableArray array];
    }
    return _productArr;
}


@end
